import { DirectiveBinding } from 'vue';
import { ElMessage } from 'element-plus';

// 声明类型扩展
interface CopyHTMLElement extends HTMLElement {
  _copyHandler?: (event: Event) => void;
  _copyValue?: () => string; // 改用函数获取最新值
  _copyCallback?: (success: boolean) => void;
}

export default {
  beforeMount(el: CopyHTMLElement, binding: DirectiveBinding) {
    initCopy(el, binding);
  },

  updated(el: CopyHTMLElement, binding: DirectiveBinding) {
    // 值变化时更新处理器
    if (binding.value !== binding.oldValue || binding.arg !== binding.oldArg) {
      cleanup(el);
      initCopy(el, binding);
    }
  },

  beforeUnmount(el: CopyHTMLElement) {
    cleanup(el);
  }
};

function initCopy(el: CopyHTMLElement, binding: DirectiveBinding) {
  // 使用函数动态获取最新值
  el._copyValue = () => binding.value;
  // 回调处理
  if (binding.arg === 'callback') {
    el._copyCallback = binding.value;
  }
  // 事件处理器（使用箭头函数保持上下文）
  el._copyHandler = async (event: Event) => {
    event.preventDefault();
    event.stopPropagation();
    const success = await copyTextToClipboard(el._copyValue!());
    el._copyCallback?.(success);
  };

  // 绑定事件
  el.addEventListener('click', el._copyHandler);
  // el.addEventListener('touchstart', el._copyHandler);
}

function cleanup(el: CopyHTMLElement) {
  if (el._copyHandler) {
    el.removeEventListener('click', el._copyHandler);
    // el.removeEventListener('touchstart', el._copyHandler);
  }
  delete el._copyHandler;
  delete el._copyValue;
  delete el._copyCallback;
}

async function copyTextToClipboard(text: string): Promise<boolean> {
  text = text.toString();
  try {
    if (navigator.clipboard?.writeText) {
      await navigator.clipboard.writeText(text);
      showSuccess();
      return true;
    }

    const textarea = document.createElement('textarea');
    textarea.value = text;
    textarea.readOnly = true; // 避免移动端自动弹出键盘
    document.body.appendChild(textarea);
    textarea.select();
    let success;
    try {
      textarea.setSelectionRange(0, text.length); // 兼容 iOS
      success = document.execCommand('copy');
    } catch (err) {
      success = false;
    }
    document.body.removeChild(textarea);

    // 兼容旧版浏览器的回退方案
    // const textarea = createHiddenTextarea(text);
    // document.body.appendChild(textarea);
    // textarea.select();
    // textarea.setSelectionRange(0, text.length); // 兼容 iOS
    //
    // const success = document.execCommand('copy');
    // console.log(success,"======success=============");
    //
    // document.body.removeChild(textarea);

    if (success) {
      showSuccess();
    } else {
      showError();
    }
    return success;
  } catch (err) {
    console.log(err);
    showError();
    return false;
  }
}

// 创建隐藏的文本域（优化版）
function createHiddenTextarea(text: string): HTMLTextAreaElement {
  const textarea = document.createElement('textarea');
  textarea.value = text;
  Object.assign(textarea.style, {
    position: 'fixed',
    top: '-9999px',
    left: '-9999px',
    opacity: '0',
    zIndex: -1000,
    pointerEvents: 'none',
    contain: 'strict',
    fontSize: '12pt',
    width: '0',
    height: '0',
    padding: '0',
    margin: '0',
    border: '0'
  });
  textarea.setAttribute('readonly', '');
  return textarea;
}

function showSuccess() {
  ElMessage.success({ message: '复制成功', showClose: true });
}

function showError() {
  ElMessage.error({ message: '复制失败，请手动复制', showClose: true });
}
